function x = hammingDecode(bin)
%Als je dit wil proberen te begrijpen kun je beter de versie in C bekijken
%omdat die een stuk duidelijker is dan deze versie. De C versie staat in 
%/Mmips/hamming.cpp

% Ook hier telt matlab vanaf de andere kant dan ons C programma, dus draai
% de vector om.
bin = bin(:,end:-1:1);

% p  = h7 ^ h6 ^ h5 ^ h4 ^ h3 ^ h2 ^ h1 ^ h0
% c0 = h7 ^ h5 ^ h1 ^ h0
% c1 = h7 ^ h3 ^ h2 ^ h1
% c2 = h5 ^ h4 ^ h3 ^ h1

p1  = xor(bin(1,8),xor(bin(1,7),xor(bin(1,6),xor(bin(1,5),xor(bin(1,4),xor(bin(1,3),xor(bin(1,2),bin(1,1))))))));
c01 = xor(bin(1,8),xor(bin(1,6),xor(bin(1,2),bin(1,1))));
c11 = xor(bin(1,8),xor(bin(1,4),xor(bin(1,3),bin(1,2))));
c21 = xor(bin(1,6),xor(bin(1,5),xor(bin(1,4),bin(1,2))));

p2  = xor(bin(2,8),xor(bin(2,7),xor(bin(2,6),xor(bin(2,5),xor(bin(2,4),xor(bin(2,3),xor(bin(2,2),bin(2,1))))))));
c02 = xor(bin(2,8),xor(bin(2,6),xor(bin(2,2),bin(2,1))));
c12 = xor(bin(2,8),xor(bin(2,4),xor(bin(2,3),bin(2,2))));
c22 = xor(bin(2,6),xor(bin(2,5),xor(bin(2,4),bin(2,2))));

% If the parity, p, is correct (equal to 1) then either 0 or 2 errors occurred. If all the check bits, c0, c1, c2 are correct (equal to 1) then the byte was received intact, (no errors) otherwise it was damaged beyond repair (two errors).
if((p1 && ~(c01 && c11 && c21)) || (p2 && ~(c02 && c12 && c22)))
    x = 255;
    return
end

% h7, h5, h3, h1
x = [bin(2,8), bin(2,6), bin(2,4), bin(2,2), bin(1,8), bin(1,6), bin(1,4), bin(1,2)];

% c0 c1 c2    meaning
% 0  0  1    error in bit h7
% 0  1  0    error in bit h5
% 1  0  0    error in bit h3
% 0  0  0    error in bit h1
if(~p2)
    if(~c02 && ~c12 && c22)
        x(1) = ~x(1);
    elseif(~c02 && c12 && ~c22)
        x(2) = ~x(2);
    elseif(c02 && ~c12 && ~c22)
        x(3) = ~x(3);
    elseif(~c02 && ~c12 && ~c22)
        x(4) = ~x(4);
    end
end
if(~p1)
    if(~c01 && ~c11 && c21)
        x(5) = ~x(5);
    elseif(~c01 && c11 && ~c21)
        x(6) = ~x(6);
    elseif(c01 && ~c11 && ~c21)
        x(7) = ~x(7);
    elseif(~c01 && ~c11 && ~c21)
        x(8) = ~x(8);
    end
end

% Terug draaien en omzetten naar een string.
x = sprintf('%i%i%i%i%i%i%i%i', x(1), x(2), x(3), x(4), x(5), x(6), x(7), x(8));
x = bin2dec(x);

end

